"""
小汽车级别分类预测
"""
import numpy as np
import pandas as pd
import sklearn.preprocessing as sp
import sklearn.ensemble as se
import sklearn.model_selection as ms

data = pd.read_csv('car.txt',header=None)
print(data)

# 数据预处理，标签编码，将字符串转为数值
train_data = pd.DataFrame()
encoders = {}
for i in data:
    encoder = sp.LabelEncoder()
    res = encoder.fit_transform(data[i])
    train_data[i] = res
    encoders[i] = encoder

# print(train_data)
# 整理输入集和输出集
x = train_data.iloc[:,:-1]
y = train_data.iloc[:,-1]
# 构建随机林森模型
model = se.RandomForestClassifier(max_depth=10,
                                  n_estimators=150,
                                  random_state=7)

# 验证曲线，寻找最优模型参数
# params = np.arange(50,551,50)
# params = np.arange(100,151,10)
# train_scores,test_scores = ms.validation_curve(model,x,y,param_name='n_estimators',param_range=params,cv=5)
# print(test_scores)
# print(test_scores.mean(axis=1))

# max_depth
# params = np.arange(2,7,1)
params = np.arange(10,15,1)
train_scores,test_scores = ms.validation_curve(model,x,y,param_name='max_depth',param_range=params,cv=5)
# print(test_scores)
print(test_scores.mean(axis=1))
# 模型训练
model.fit(x,y)

test_data = [['high','med','5more','4','big','low','unacc'],
             ['high','high','4','4','med','med','acc'],
             ['low','low','2','4','small','high','good'],
              ['low','med','3','4','med','high','vgood']]

test_data = pd.DataFrame(test_data)
# print(test_data)
for i in test_data:
    encoder = encoders[i]
    res = encoder.transform(test_data[i])
    test_data[i] = res
# print(test_data)

# 划分测试集输入和输出
test_x = test_data.iloc[:,:-1]
test_y = test_data.iloc[:,-1]
pred_test_y = model.predict(test_x)
# print(pred_test_y)
print(encoders[6].inverse_transform(pred_test_y))
# 测试

print(train_data[6].value_counts())
